using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Gko.Wpf.Mvvm.Interfaces;

namespace Gko.Wpf.Mvvm
{
	public abstract class ModalViewModelBase : WindowViewModelBase, IModalViewModel
	{
		private readonly DelegateCommand acceptCommand;
		private readonly DelegateCommand cancelCommand;
		private bool isClosingByCommand;

		protected ModalViewModelBase(IViewModelContext context)
			: base(context)
		{
			this.acceptCommand = new DelegateCommand(this.OnAccept, this.CanAccept);
			this.cancelCommand = new DelegateCommand(this.OnCancel, this.CanCancel);
		}

		protected virtual bool IsAllowUserToCloseView
		{
			get
			{
				return false;
			}
		}

		#region IModalViewModel Members

		public bool? DialogResult
		{
			get;
			private set;
		}

		public ICommand AcceptCommand
		{
			get
			{
				return this.acceptCommand;
			}
		}

		public ICommand CancelCommand
		{
			get
			{
				return this.cancelCommand;
			}
		}

		public override void OnViewClosing(CancelEventArgs e)
		{
			var allowClosing = this.IsAllowUserToCloseView || this.isClosingByCommand;
			e.Cancel = !allowClosing;
		}

		#endregion

		protected virtual bool CanCancel()
		{
			return true;
		}

		protected virtual void OnCancel()
		{
			this.DialogResult = false;
			this.OnClose();
		}

		protected override void OnClose()
		{
			this.isClosingByCommand = true;
			base.OnClose();
		}

		protected virtual bool CanAccept()
		{
			return true;
		}

		protected virtual void OnAccept()
		{
			this.DialogResult = true;
			this.OnClose();
		}
	}
}